package com.changgou.search.controller;

import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Set;

/**
 * Created by 柱子 on 2020/10/22 21:23   多条件商品查询
 */

@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;


    /**
     * thymeleaf静态页面生成
     *
     * @return
     */
    @GetMapping("/list")
    public String search(@RequestParam Map<String, String> searchMap, Model model) {

        //特殊符号处理
        this.handlerSearchMap(searchMap);

        //获取查询结果

        Map resultMap = searchService.search(searchMap);

        //发送Thymeleaf
        model.addAttribute("result", resultMap);
        model.addAttribute("searchMap", searchMap);

        return "search";


    }


    /**
     * 全文检索
     *
     * @return
     */
    @GetMapping
    public Map search(@RequestParam Map<String, String> paramMap) {
        //特殊符号处理
        this.handlerSearchMap(paramMap);
        Map searchMap = searchService.search(paramMap);
        return searchMap;

    }

    /**
     * 将搜索传入的条件进行处理
     *
     * @param paramMap 搜索查询参数
     */
    private void handlerSearchMap(Map<String, String> paramMap) {
        if (paramMap != null) {
            Set<Map.Entry<String, String>> entries = paramMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")) {
                    paramMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));

                }

            }
        }
    }


}
